<template>
  <view>
    <u-toast ref="uToast" />
    <!-- 这里才是小程序代码 -->
    <u-popup
      class="coreshop-bottom-popup-box"
      :show="showLogin"
      @close="hideModal"
      :safeAreaInsetBottom="false"
      mode="center"
    >
      <view
        class="radius coreshop-bg-white"
        style="background-color: #fff; border-radius: 8px; width: 305px"
      >
        <view class="modal-box" style="width: 272px">
          <view class="modal-box-detail-detail">
            <!--      <view class="shopDesc">
              <view class="coreshop-avatar sm round margin-left">
                <u--image width="24px" height="24px" :src="shopLogo"></u--image>
              </view>
              <text class="shopName">{{ shopName || "登录授权" }}</text>
              <text class="get">申请</text>
            </view>
            <view class="modal-box-detail-title3"
              >获取以下权限为您提供服务</view
            >
            <view class="modal-box-detail-desc">
              1、获取你的手机号提供更好的账户安全，物流，订单状态提醒等服务（在接下来微信授权手机号的弹窗中选择“允许”）<br />
              2、使用我们的相关服务，需要将您的手机号授权给我们。
            </view> -->
            <view
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                margin-top: 20px;
                border-radius: 8px;
              "
            >
              <view class="" style="margin: 6px">
                <u--image
                  width="50px"
                  height="50px"
                  :src="shopLogo"
                  shape="circle"
                ></u--image>
              </view>
              <view style="margin-left: 10px">
                <view
                  class="coreshop-font-lg coreshop-font-weight-bold"
                  style="font-weight: bold; font-size: 15px"
                  >您还未登录</view
                >
                <view
                  class="coreshop-font-sm c-m-t-5"
                  style="font-size: 13px; margin-top: 5px"
                  >请先登录再进行操作</view
                >
              </view>
            </view>
            <view class="c-m-t-30" style="margin-top: 30px">
              <u-button
                v-if="isDisabled"
                color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
                @click="showrtxt = true"
              >
                手机号快捷登录
              </u-button>
              <u-button
                v-else
                color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
                open-type="getPhoneNumber"
                @getphonenumber="getPhoneNumber"
              >
                手机号快捷登录
              </u-button>
            </view>
            <!-- 服务协议 -->
            <view class="coreshop-margin-top-15 agreement-checked-view">
              <view class="agreement-text-prompt" v-if="showrtxt"
                >请阅读并勾选用户协议</view
              >
              <u-checkbox-group>
                <u-checkbox
                  v-model="agreement"
                  :checked="agreement"
                  @change="checkboxChange"
                  size="14"
                  active-color="#ED174D"
                >
                </u-checkbox>
              </u-checkbox-group>
              <view class="coreshop-text-black-view">
                <text class="coreshop-text-black">登录代表您已同意</text>
                <text
                  class="line-blue c-m-l-5"
                  style="color: #0081ff"
                  @tap="goUserAgreementPage"
                  >十八颜用户服务协议、</text
                >
                <text
                  class="line-blue"
                  style="color: #0081ff"
                  @tap="goUserPrivacyPolicy"
                  >隐私政策</text
                >
              </view>
            </view>
          </view>
          <!-- <view
						class="coreshop-flex coreshop-justify-between coreshop-padding-left-15 coreshop-padding-right-15">
						<view class="coreshop-padding-5"><u-button @click="closeAuth">暂不授权</u-button></view>
						<view class="coreshop-padding-5">
							<u-button type="success" :disabled="isDisabled" v-if="isDisabled">确定授权</u-button>
							<u-button type="success" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-else>确定授权</u-button>
						</view>
					</view> -->
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
/**
 * 登录提示页
 * @property {Boolean} value=showLoginTip - 由v-model控制显示隐藏。
 * @property {Boolean} forceOauth - 小程序端特制的全屏登录提示。
 */
import { mapState } from "vuex";
export default {
  name: "coreshopLoginModal",
  components: {},
  data() {
    return {
      agreement: false,
      showrtxt: false,
      isDisabled: true,
      maxMobile: 11,
      mobile: "", // 用户手机号
      code: "", // 短信验证码
      verification: true, // 通过v-show控制显示获取还是倒计时
      timer: 60, // 定义初始时间为60s
      btnb: "coreshop-btn coreshop-btn-square coreshop-btn-c coreshop-btn-all", //按钮背景
      type: "", // 有值是第三方登录账号绑定
      showCodeBox: false,
      maxlength: 6,
      //   codevalue: "",
      error: false,
      errorMsg: "验证码错误，请重新输入",
    };
  },
  props: {
    shareCode: {
      type: String,
      default: "",
    },
    value: {},
    modalType: {
      type: String,
      default: "",
    },
  },
  computed: {
    ...mapState({
      showLoginTip: (state) => state.showLoginTip,
      sessionAuthId: (state) => state.sessionAuthId,
      hasLogin: (state) => state.hasLogin,
      userInfo: (state) => state.userInfo,
      setUserStore: (state) => state.setUserStore,
    }),
    shopLogo() {
      return this.$store.state.config.shopLogo;
    },
    shopName() {
      return this.$store.state.config.shopName;
    },
    showLogin: {
      get() {
        // return this.showLoginTip;
        return true;
      },
      set(val) {
        this.$store.commit("showLoginTip", val);
      },
    },
    sessionAuthIdTool: {
      get() {
        return this.sessionAuthId;
      },
      set(val) {
        this.$store.commit("sessionAuthId", val);
      },
    },

    // 动态更改登录按钮bg
    regButtonClass() {
      return this.mobile && this.mobile.length === this.maxMobile && this.code
        ? this.btnb + " coreshop-btn-b"
        : this.btnb;
    },
  },
  mounted() {
    const _this = this;
    // #ifdef MP-WEIXIN
    var userInfo = this.$store.state.userInfo;
    //var token = this.$db.get('userToken');
    if (Object.keys(userInfo).length != 0) {
      //console.log("获取到store.state用户数据");
    } else {
      _this.doToken();
    }
    // #endif
  },
  //watch: {
  //    'hasLogin': {
  //        handler(newVal) {
  //            //console.log(newVal);
  //            if (newVal == false) {
  //                //console.log("watch监听");
  //                this.doToken();
  //            }
  //        },
  //        deep: true,
  //        immediate: true,
  //    }
  //},
  onShow() {
    let _this = this;
    _this.timer = parseInt(_this.$db.get("timer"));
    if (_this.timer != null && _this.timer > 0) {
      _this.countDown();
      _this.verification = false;
    }
  },
  methods: {
    submit() {
      if (this.$u.test.mobile(this.mobile)) {
        this.sendCode();
      } else {
        this.$u.toast("请输入合法的手机号码!");
      }
    },
    // 收不到验证码选择时的选择
    /*     noCaptcha() {
      var _this = this;
      uni.showActionSheet({
        itemList: ["重新获取验证码"],
        success: function (res) {
          _this.sendCode();
        },
        fail: function (res) {
          this.$u.toast("重发失败!");
        },
      });
    }, */
    // change事件侦听
    change(value) {
      console.log("change", value);
    },
    // 输入完验证码最后一位执行
    finish(value) {
      this.code = value;
      if (this.sessionAuthIdTool) {
        this.toBind();
      } else {
        this.login();
      }
    },
    // 发送短信验证码
    sendCode() {
      if (!this.rightMobile.status) {
        this.$u.toast(this.rightMobile.msg);
      } else {
        uni.showToast({
          title: "发送中...",
          icon: "loading",
        });
        setTimeout(() => {
          uni.hideToast();
          this.$u.api
            .sms({
              mobile: this.mobile,
              code: "login",
            })
            .then((res) => {
              if (res.status) {
                this.showCodeBox = true;
                this.timer = 60;
                this.verification = false;
                this.$refs.uToast.show({
                  message: res.msg,
                  type: "success",
                });
                this.countDown(); // 执行验证码计时
              } else {
                this.$u.toast(res.msg);
              }
            });
        }, 1000);
      }
    },
    // 验证码倒计时
    countDown() {
      let auth_timer = setInterval(() => {
        // 定时器设置每秒递减
        this.timer--; // 递减时间
        uni.setStorage({
          key: "timer",
          data: this.timer,
          success: function () {},
        });
        if (this.timer <= 0) {
          this.verification = true; // 60s时间结束还原v-show状态并清除定时器
          clearInterval(auth_timer);
        }
      }, 1000);
    },
    // 登录
    login() {
      var _this = this;
      if (!_this.rightMobile.status) {
        _this.$u.toast(_this.rightMobile.msg);
      } else {
        // 短信验证码登录
        if (!_this.code) {
          _this.$u.toast("请输入短信验证码!");
        } else {
          let data = {
            mobile: _this.mobile,
            code: _this.code,
          };

          let invicode = _this.$db.get("invitecode");
          if (invicode) {
            data.invitecode = invicode;
          }

          _this.$u.api.smsLogin(data).then((res) => {
            if (res.status) {
              this.$db.set("userToken", res.data.token);
              _this.redirectHandler(res.msg);
            } else {
              _this.$u.toast(res.msg);
              _this.error = true;
              _this.errorMsg = res.msg;
            }
          });
        }
      }
    },
    // 重定向跳转 或者返回上一个页面
    redirectHandler(msg) {
      let _this = this;
      this.$refs.uToast.show({
        message: msg,
        type: "success",
        complete: function () {
          _this.$db.set("timer", 0);
          _this.$db.del("invitecode");
          _this.showLogin = false;
          _this.toLoginSuccessHandleBack();
        },
      });
    },
    doToken() {
      const _this = this;
      //console.log("重新获取用户数据");
      _this.getCode(function (code) {
        let data = {
          code: code,
          // appid: uni.getAppBaseInfo().host.appId  // 真机调试 线上版本无法获取appid 换成uni.getAccountInfoSync().miniProgram.appId
          appid: uni.getAccountInfoSync().miniProgram.appId,
        };
        /* 	_this.$u.api.onLogin(data).then(res => {
						if (res.status) {
							if (res.data.auth) {
								_this.$db.set('userToken', res.data.auth.token)
								_this.$store.commit('hasLogin', true);
							}
							if (res.data.user) {
								_this.$store.commit('userInfo', res.data.user);
							}
							if(res.data.store){
								_this.$store.commit('setUserStore',{
									id:res.data.store.id,
									name:res.data.store.storeName,
									mobile:res.data.store.mobile,
									address:res.data.store.address,
								})
							}
							_this.sessionAuthIdTool = res.otherData;
							//console.log("成功后获取sessionAuthIdTool：" + _this.sessionAuthIdTool);
						} else {
							_this.sessionAuthIdTool = res.otherData;
							//console.log("失败后获取sessionAuthIdTool：" + _this.sessionAuthIdTool);
						}
					}) */
      });
    },
    // 勾选版权协议
    checkboxChange(e) {
      this.agreement = e;
      if (e == true) {
        this.isDisabled = false;
        this.showrtxt = false;
      } else {
        this.isDisabled = true;
      }
    },
    // 隐藏登录弹窗
    hideModal() {
      this.showLogin = false;
    },

    // 小程序，取消登录
    closeAuth() {
      this.showLogin = false;
      // this.$u.toast('您已取消授权')
    },
    getCode: function (callback) {
      let _this = this;
      uni.login({
        // #ifdef MP-ALIPAY
        scopes: "auth_user",
        // #endif
        success: function (res) {
          if (res.code) {
            return callback(res.code);
          } else {
            //login成功，但是没有取到code
            _this.$refs.uToast.show({
              message: "未取得code，请重试",
              type: "error",
            });
          }
        },
        fail: function (res) {
          //console.log(res);
          var scene = this.$store.state.scene;
          //判断是否为 朋友圈内打开“单页模式"，单页模式下，数据交互无法执行。所以不进行提醒
          if (scene != 1154) {
            _this.$refs.uToast.show({
              message: "用户授权失败wx.login，请重试",
              type: "error",
            });
          }
        },
      });
    },
    toLogin: function (data) {
      let _this = this;
      _this.$u.api.loginByDecodeEncryptedData(data).then((res) => {
        if (res.status) {
          //判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
          if (res.data.token) {
            //登陆成功，设置token，并返回上一页
            _this.$db.set("userToken", res.data.token);
            _this.$store.commit("hasLogin", true);
            _this.$refs.uToast.show({
              message: "登录成功",
              type: "success",
            });
            return false;
          } else {
            // #ifdef MP-WEIXIN
            _this.sessionAuthIdTool = res.data.sessionAuthId;
            // #endif
            // #ifndef MP-WEIXIN
            _this.$u.route({
              type: "navigateTo",
              url:
                "/pages/login/loginBySMS/loginBySMS?sessionAuthId=" +
                res.data.sessionAuthId,
            });
            // #endif
          }
        } else {
          _this.$refs.uToast.show({
            message: "登录失败，请重试",
            type: "error",
          });
        }
      });
    },
    /**
     * 手机号登录
     * @param e
     */
    async getPhoneNumber(e) {
      let _this = this;
      _this.showLogin = false;
      console.log("e", e);

      if (e.mp.detail.errMsg == "getPhoneNumber:ok") {
        var data = {
          sessionAuthId: _this.sessionAuthIdTool,
          iv: e.mp.detail.iv,
          shareCode: _this.shareCode,
          encryptedData: e.mp.detail.encryptedData,
          appid: uni.getAccountInfoSync().miniProgram.appId,
        };

        //有推荐码的话，带上
        /*         var invitecode = _this.$db.get("invitecode");
        if (invitecode) {
          data.invitecode = invitecode;
        } */
        console.log("data-->", data);
        _this.toGetPhoneNumber(data);
      } else {
        _this.$u.toast("如未授权，您可尝试使用手机号+短信验证码登录");
      }
    },
    //实际的去登陆
    toGetPhoneNumber: function (data) {
      let _this = this;
      _this.$u.api.loginByGetPhoneNumber(data).then((res) => {
        if (res.status) {
          if (res.otherData) {
            _this.$store.commit("userInfo", res.otherData);
          }
          //判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
          if (res.data.token) {
            //console.log("登陆成功，设置token，并返回上一页");
            //登陆成功，设置token，并返回上一页
            _this.$db.set("userToken", res.data.token);
            _this.$store.commit("hasLogin", true);
            _this.showLogin = false;
            _this.$refs.uToast.show({
              message: "登录成功!",
              type: "success",
            });
            _this.$emit("changeEvent", true);
            return false;
          }
        } else if (res.status == false && res.code == 500) {
          //console.log("sessionId不正确，重载");
          _this.$u.route({
            type: "switchTab",
            url: "/pages/index/default/default",
          });
        } else {
          _this.$u.toast("登录失败，请重试");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "coreshop-login-modal.scss";
</style>
